package com.sc.site.cart;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.sc.dal.dto.promotion.PromotionDetailDto;
import com.sc.dal.dto.promotion.PromotionGoodsSkuDto;
import com.sc.dal.model.cart.Cart;
import com.sc.dal.model.cart.CartItem;
import com.sc.dal.model.cart.Shop;
import com.sc.dal.model.favorites.Favorites;
import com.sc.dal.model.goods.Goods;
import com.sc.dal.model.goods.GoodsStock;
import com.sc.dal.model.member.Member;
import com.sc.service.cart.CartService;
import com.sc.service.favorites.FavoritesService;
import com.sc.service.goods.GoodsService;
import com.sc.service.goods.GoodsSkuService;
import com.sc.service.member.MemberService;
import com.sc.service.promotion.PromotionService;
import com.sc.site.BaseController;
import com.sc.util.adapter.ConfigBeanAdapter;
import com.sc.util.data.Common;
import com.sc.util.data.Constants;
import com.sc.util.data.DataUtil;
import com.sc.util.data.SessionContainer;
import com.sc.util.exception.ExceptionEnum;
/**
 * @ClassName: AppCartController
 * @Description: 购物车管理
 * @author LeiJia
 * @date 2017年3月8日 下午1:59:26
 * @version V1.0
 */
@Controller
@RequestMapping("/cart")
public class CartController extends BaseController{
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());	
	
	@Autowired
	private CartService cartService;
	
	@Autowired
	private FavoritesService favoritesService;	
	
	@Autowired
	private GoodsService goodsService;
	
	@Autowired
	private GoodsSkuService goodsSkuService;
	
	@Autowired
	private MemberService memberService;
	
	@Autowired
	private PromotionService promotionService;
	
	/**
	 * @Title: addProduct
	 *  @Description:添加商品到购物车
	 * @param product_id
	 * @param goods_sku_id
	 * @param goods_sku_info
	 * @param memberId
	 * @param mount 商品的最终数量
	 * @date 2017年3月9日下午14:27:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="/addProduct",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> addProduct(HttpServletRequest request,HttpServletResponse response,Integer productId ,String goods_sku_id,String goods_sku_info, String memberId,Integer mount){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try{

			Member member = SessionContainer.getSessionMember(request);
			if(member == null){
				resultMap.put("sessionValid", true); //会话失效
				return resultMap;
			}
			if(productId == null || Common.isEmpty(memberId)  || mount == null){				
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
		    }
            Cart cart = new Cart();
            cart.setId(Common.getUUID());
            cart.setSellerId(Constants.SELLERID);
            cart.setCreateDate(new Date());
            cart.setCreater(memberId);
            cart.setIsValid(Constants.IS_VALIDA);
            cart.setSelected(Constants.CartProduct.IS_SELECTEDA);
            cart.setIsDelete(Constants.CartProduct.IS_DELETEA);
            cart.setProductId(productId);
            cart.setMemberId(memberId);
            cart.setModifier(memberId);
            cart.setModifyDate(new Date());  
            if(Common.isNotEmpty(goods_sku_id)){
                cart.setGoods_sku_id(goods_sku_id);
    			String[] goods_sku_ids = goods_sku_id.split(",");
    			String goods_sku_values="";
    			if(goods_sku_ids.length > 0){
    				for(String sku_id: goods_sku_ids){
    					Map<String,Object> paramMap = new LinkedHashMap<String, Object>();	
    					paramMap.put("goods_sku_id", sku_id);
    					paramMap = goodsSkuService.selectGoodsSkuById(paramMap);
    					if(paramMap != null && paramMap.size() > 0){
    						goods_sku_values += paramMap.get("base_sku_name").toString() +":"+ paramMap.get("base_sku_value_name").toString() +",";
    					}
    				}
    			}
                cart.setGoods_sku_info(goods_sku_values);
            }
            int i =0;
        	List<Cart> list = cartService.selectByCartInfo(cart);
    		if(list == null || list.size() <1){
    			cart.setQuantity(mount);
    		    i = cartService.insert(cart);
    		}else{
        		//如果商品在购物车中已经存在,quantity数量增加mount
        		Cart c =list.get(0);
        		c.setGoods_sku_id(cart.getGoods_sku_id());
        		c.setGoods_sku_info(cart.getGoods_sku_info());
        		c.setQuantity(c.getQuantity() +mount);
        		c.setSelected(cart.getSelected());
        		c.setIsDelete(cart.getIsDelete());
        		c.setIsValid(cart.getIsValid());
        		c.setModifyDate(new Date());
        		i = cartService.updateCart(c);
    		}
			//int i = cartService.addProduct(cart,mount);
			if(i >0){
				cartService.updateSessionCookieCartCount(request,response);//更新session或cookie购物车中的商品数量
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
			}else{
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_INSERT);
			}
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_FAIL);
		}
		return resultMap;
	}


	/**
	 * @Title: moveToFavorites
	 * @Description:编辑购物车移入收藏夹
	 * @param carts
	 * @date 2017年3月10日上午10:40:05
	 * @author LeiJia  
	 * @return Map<String,Object>    返回类型
	 */
	@RequestMapping(value="/moveToFavorites",method=RequestMethod.POST)
	@ResponseBody
	@Transactional
	public Map<String, Object> moveToFavorites(HttpServletRequest request,HttpServletResponse response) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			String ids = getPara("ids"); //商品购物车ID
			String collectionType = getPara("collectionType");
			Member member = SessionContainer.getSessionMember(request);
			if (member == null) {
				resultMap.put("sessionValid", true); // 会话失效
				return resultMap;
			}
			if (Common.isEmpty(ids)) {
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}
			String[] idsArr = ids.split(",");
			if (idsArr == null || idsArr.length == 0) {
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PARAM);
				return resultMap;
			}
			for (int i = 0; i < idsArr.length; i++) {

				// 修改购物车商品状态
				Cart cart = new Cart();
				cart = cartService.getCartByCartId(idsArr[i]);
				Favorites favorite = new Favorites();
				favorite.setGoodsId(cart.getProductId());
				favorite.setCollectionType(collectionType);
				favorite.setmId(member.getmId());
				// 添加收藏
				favorite.setId(Common.getUUID());
				favorite.setCreateDate(new Date());
				favorite.setCreater(member.getmId());
				favorite.setModifier(member.getmId());
				favorite.setCollectionType(Constants.CartProduct.COLLECTION_TYPEA);
				favorite.setModifyDate(new Date());
				favorite.setIsDelete(Constants.CartProduct.IS_DELETEA);
				int insertFavorite = favoritesService.insert(favorite);
				if (insertFavorite > 0) {
					DataUtil.handleResultMap(resultMap,	ExceptionEnum.DATA_SUCCESS);
				} else {
					DataUtil.handleResultMap(resultMap,ExceptionEnum.DATA_INSERT);
				}
				if (cart != null) {
					// 修改购物车商品为已添加到收藏夹，删除购物车中的该商品
					cart.setSelected(Constants.CartProduct.IS_SELECTEDB);
					cart.setIsDelete(Constants.IS_DELETEB);
					int upateCartResult = cartService.updateCart(cart);
					if (upateCartResult > 0) {
						DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
						logger.info("商品已被收藏，购物车中该商品已移除！");
					} else {
						DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_INSERT);
						logger.info("商品已被收藏，购物车中该商品添加收藏失败！");
					}
				}
			}

			cartService.updateSessionCookieCartCount(request,response);//更新session或cookie购物车中的商品数量
		} catch (Exception e) {
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_INSERT);
		}
		return resultMap;
	}
	/**
	 * @Title: addOrCacelFavorites
	 * @Description:商品详情页添加或取消商品收藏
	 * @param mId
	 * @param goodsId
	 * @param sellerId
	 * @param collectionType
	 * @param selected 商品是否已被收藏（0：否，1：是）
	 * @return
	 */
	@RequestMapping(value="/addOrCacelFavorites",method=RequestMethod.POST)
	@ResponseBody
	public Map<String ,Object> addFavorites(HttpServletRequest request,HttpServletResponse response,Integer goodsId, String sellerId, String collectionType,String selected){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Favorites favorite = new Favorites();

    	try{
			Member member = SessionContainer.getSessionMember(request);
			if (member == null) {
				resultMap.put("sessionValid", true); // 会话失效
				return resultMap;
			}
			favorite.setmId(member.getmId());
			favorite.setGoodsId(goodsId); 
			favorite.setSellerId(Constants.SELLERID);   	
	    	favorite.setCollectionType(collectionType);
	    	favorite.setCreateDate(new Date());
	    	favorite.setCreater(member.getmId());
	    	favorite.setModifier(member.getmId());
	    	favorite.setModifyDate(new Date()); 
    		if(selected.equals("1")){
                //添加收藏	    	
    	    	favorite.setIsDelete(Constants.CartProduct.IS_DELETEA);//商品是否要删除 是否删除（0：没有删除；1：删除）
    	    	//判断该用户是否收藏了该商品
        		Favorites f =favoritesService.selectByParam(favorite);
        		if(f != null){
    				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PRODUCT_HAS_ADDED_FAVORITES);
    				return resultMap;
        		}
        		
    	    	favorite.setId(Common.getUUID());
    			int i = favoritesService.insert(favorite);
    			if(i>0){
        			logger.info("添加收藏夹成功！");
    				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PRODUCT_ADD_TO_FAVORITES_IS_SUCCESS);
    				return resultMap;
    			}else{
        			logger.info("添加收藏夹失败！");
    				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PRODUCT_ADD_TO_FAVORITES_IS_ERROR);
    				return resultMap;
    			}

    		
        	}else if(selected.equals("0")){
        		//取消收藏
    	    	favorite.setIsDelete(Constants.CartProduct.IS_DELETEA);//商品是否要删除 是否删除（0：没有删除；1：删除）
        		Favorites cancelF =favoritesService.selectByParam(favorite);
        		if(cancelF == null){
        			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_FAVORITES_PRODUCT_IS_NOT_FIND);
        			return resultMap;
        		}
        		cancelF.setIsDelete(Constants.FavoriteProduct.IS_DELETEB);
        		int deleteFavirteProductResult = favoritesService.updateByPrimaryKeySelective(cancelF);
        		if(deleteFavirteProductResult > 0){
        			logger.info("商品取消收藏成功！");
    				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PRODUCT_REMOVE_FROM_FAVORITES_IS_SUCCESS);
    				return resultMap;
        		}else{
        			logger.info("商品取消收藏失败 ！");
    				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PRODUCT_REMOVE_FROM_FAVORITES_IS_ERROR);
    				return resultMap;
        		}
        	} 

			cartService.updateSessionCookieCartCount(request,response);//更新session或cookie购物车中的商品数量
    	}catch(Exception e){
    		e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_UPDATE);
    		
    	}
		return resultMap;
	}
	/**
	 * @Title: cartPage
	 * @Description:获取购物车
	 * @param model
	 * @param request
	 * @date 2017年4月21日上午11:21:09
	 * @author LeiJia  
	 * @return String   返回类型
	 */
	@RequestMapping(value="/cartPage")
	public String cartPage(Model model,HttpServletRequest request,HttpServletResponse response){			
		List<Shop> shops = new ArrayList<Shop>();//全部商品与店铺
		List<Shop>  privilegShops = new ArrayList<Shop>(); //参与优惠的商品与店铺
		List<Shop>  shortStockShops = new ArrayList<Shop>(); //库存不足的商品与店铺
		List<CartItem> resultList = new ArrayList<CartItem>();//全部购物车项
		int allTotal = 0; //全部商品数量
		int privilegeTotal = 0; //优惠商品数量
		int shortStockTotal = 0; //库存不足商品
		//页面传过来的查询条件
		String cartType = getPara("cartType");	
		try{
			Member member = SessionContainer.getSessionMember(request);
			if(member == null){
				return "redirect:/member/loginPre?redirect=/cart/cartPage";
			}
			CartItem cart = new CartItem();
			cart.setMemberId(member.getmId());
			shops = cartService.cartShopList(cart);		
			//String memberId = member.getmId();
			//Map<String,Object> paramMap = new LinkedHashMap<String, Object>();
			// 添加查询条件
			//paramMap.put("memberId", memberId);
			for(Shop shop :shops){
				//resultList = cartService.selectByMapParam(paramMap);
				resultList = shop.getCartItems();				
				allTotal += resultList.size();
				
				Shop privilegShop = new Shop();
				List<CartItem> privilegShopItem = privilegShop.getCartItems();
				Shop stockShop =new Shop();
				List<CartItem> stockShopItem = stockShop.getCartItems();
				//根据商品规格确定库存
				for (CartItem item : resultList) {
					// 根据会员的代理商等级查询代理等级的商品折扣率
					Map<String, Object> agentInfoMap = memberService.selectAgentInfoByMemberId(item.getMemberId());
					if (agentInfoMap != null && agentInfoMap.size() > 0) {
						if (agentInfoMap.get("discount") != null) {
							double discount = (double) agentInfoMap.get("discount");
							item.setDiscountMarketPrice(item.getMarketPrice().multiply(new BigDecimal(discount)).setScale(2, BigDecimal.ROUND_HALF_UP));
							item.setDiscountRate(discount);
						}
					}
					if (Common.isNotEmpty(item.getPicture()))
						item.setPicture(ConfigBeanAdapter.fileAccessAddress + item.getPicture());
					String skuInfos = item.getGoods_sku_info();
					String[] skuInfoArrs = {};
					if (Common.isNotEmpty(skuInfos)) {
						skuInfoArrs = skuInfos.split(",");

					}
					GoodsStock stock = new GoodsStock();
					stock.setGoodsId(item.getProductId());
					int productStock = goodsService.getProductStock(stock,skuInfoArrs);
					item.setStock(productStock + "");
					if (productStock <= 0) {  //对于购物车库存为0的商品设为失效状态，对于购物车商品数量超出商品库存的商品在结算时候给予提示修改购物车数量
						// 如果对应规格零库存
						item.setIsValid(Constants.IS_VALIDB);
						Cart c = new Cart();
						c.setId(item.getId());
						c.setIsValid(Constants.IS_VALIDB);
						c.setIsDelete(Constants.IS_DELETEA);
						c.setModifyDate(new Date());
						int updateCart = cartService.updateCart(c);
						if (updateCart > 0) {
							logger.info("商品已置为无效商品!");
						}
					}
					//库存缺失
					if (productStock <= Integer.valueOf(ConfigBeanAdapter.shortStock)) {
						stockShopItem.add(item);
						shortStockTotal += 1;
					}
					//商品是否参与优惠活动
					if (productWhtherJoinPrivilege(item.getProductId(),
							item.getQuantity(), item.getMarketPrice())) {
						privilegShopItem.add(item);
						privilegeTotal += 1;
					}
				}
				stockShop.setSellerId(shop.getSellerId());
				stockShop.setMemberId(shop.getMemberId());
				stockShop.setShopName(shop.getShopName());
				privilegShop.setSellerId(shop.getSellerId());
				privilegShop.setMemberId(shop.getMemberId());
				privilegShop.setShopName(shop.getShopName());
				stockShop.setCartItems(stockShopItem);
				privilegShop.setCartItems(privilegShopItem);
				if(privilegShop.getCartItems().size() >0 && Common.isNotEmpty(privilegShop.getSellerId())){
					privilegShops.add(privilegShop);
				}
				if(stockShop.getCartItems().size() >0 && Common.isNotEmpty(stockShop.getSellerId())){
					shortStockShops.add(stockShop);
				}
				
			}
			if("all".equals(cartType)){
				//全部商品
				model.addAttribute("shops", shops);
			}else if("privilege".equals(cartType)){
				//全部优惠商品
				model.addAttribute("shops", privilegShops);
			}else if("shortStock".equals(cartType)){
				//库存紧张商品
				model.addAttribute("shops", shortStockShops);
			}else{
				//全部商品
				model.addAttribute("shops", shops);
			}
			model.addAttribute("allTotal", allTotal);
			model.addAttribute("privilegeTotal", privilegeTotal);
			model.addAttribute("shortStockTotal", shortStockTotal);

			cartService.updateSessionCookieCartCount(request,response);//更新session或cookie购物车中的商品数量
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return "/cart/shopping_cart";
	}
	/**
	 * @Title: deleteProduct
	 * @Description:编辑购物车删除购物车商品
	 * @date 2017年4月22日上午08:18:05
	 * @author LeiJia  
	 * @return JSONObject   返回类型
	 */
	@RequestMapping(value="/deleteProduct")
	@ResponseBody
	public JSONObject deleteProduct(HttpServletRequest request,HttpServletResponse response) {
		JSONObject json = new JSONObject();
		String id = getPara("id");
		try {
			if (Common.isEmpty(id)) {
				json.put("flag", false);
				return json;
			}
			Cart cart = new Cart();
			cart.setId(id);
			cart.setIsDelete(Constants.CartProduct.IS_DELETEB);
			int i = cartService.deleteProduct(cart);
			if (i > 0) {
				cartService.updateSessionCookieCartCount(request,response);//更新session或cookie购物车中的商品数量
				json.put("flag", true);
			}
		} catch (Exception e) {
			e.printStackTrace();
			json.put("flag", false);
		}
		return json;
	}
	/**
	 * @Title: deleteAllProduct
	 * @Description:批量删除购物车商品
	 * @date 2017年4月22日上午08:18:05
	 * @author LeiJia  
	 * @return JSONObject    返回类型
	 */
	@RequestMapping(value="/deleteAllProduct")
	@ResponseBody
	public JSONObject deleteAllProduct(HttpServletRequest request,HttpServletResponse response){
		JSONObject json = new JSONObject();
		String ids = getPara("ids");
		try{
			if(Common.isEmpty(ids)){
				json.put("flag", false);
				return json; 
			}
			String[] idsArr = ids.split(",");
			if(idsArr == null || idsArr.length == 0 ){
				json.put("flag", false);
				return json; 
			}			
		   for(int i = 0; i < idsArr.length ; i++){
				Cart cart = new Cart();
				cart.setId(idsArr[i]);
				cart.setIsDelete(Constants.CartProduct.IS_DELETEB);
			    cartService.deleteProduct(cart);
		   }
		   json.put("flag", true);
			cartService.updateSessionCookieCartCount(request,response);//更新session或cookie购物车中的商品数量
		}catch(Exception e){
			e.printStackTrace();
			json.put("flag", false);
		}
		return json;
	}

	/**
	 * @Title: clearShortStockInvalidPorduct
	 * @Description: 清除购物车中因库存缺失而失效的商品
	 * @date 2017年4月23日上午11:18:05
	 * @author LeiJia  
	 * @return JSONObject    返回类型
	 */
	@RequestMapping(value="/clearShortStockInvalidPorduct")
	@ResponseBody
	public JSONObject clearShortStockInvalidPorduct(HttpServletRequest request,HttpServletResponse response) {
		List<Shop> shops = new ArrayList<Shop>();// 全部商品与店铺
		JSONObject json = new JSONObject();
		try {
			Member member = SessionContainer.getSessionMember(request);// 根据sessionId获取登录用户
			if (member == null) {
				json.put("sessionValid", true); //会话失效
				return json;
			}
			CartItem cart = new CartItem();
			cart.setMemberId(member.getmId());
			shops = cartService.cartShopList(cart);

			for (Shop shop : shops) {
				// resultList = cartService.selectByMapParam(paramMap);
				List<CartItem> resultList = shop.getCartItems();
				// 根据商品规格确定库存
				for (CartItem item : resultList) {
					String skuInfos = item.getGoods_sku_info();
					if (Common.isNotEmpty(skuInfos)) {
						String[] skuInfoArrs = skuInfos.split(",");
						GoodsStock stock = new GoodsStock();
						stock.setGoodsId(item.getProductId());
						int productStock = goodsService.getProductStock(stock,
								skuInfoArrs);
						item.setStock(productStock + "");
						if (item.getStock().equals("0")  || item.getIsValid().equals(Constants.IS_VALIDB)) {
							// 如果对应规格零库存 清除掉该商品
							Cart  c= new Cart();
							c.setId(item.getId());
							c.setIsValid(Constants.IS_VALIDB);
							c.setIsDelete(Constants.CartProduct.IS_DELETEB);
						    int deleteProduct = cartService.deleteProduct(c);
						    if(deleteProduct >0){
						    	logger.info("清除失效商品成功!");
						    }else{
						    	logger.info("清除失效商品失败!");
						    }
						}
					}
				}

			}

			cartService.updateSessionCookieCartCount(request,response);//更新session或cookie购物车中的商品数量
	    	json.put("flag", true);
		} catch (Exception e) {
			e.printStackTrace();
	    	json.put("flag", false);
		}
		return json;
	}
	
	/**
	 * @Title: updateProduct
	 * @Description: 修改购物车商品数量
	 * @date 2017年4月23日上午10:05:05
	 * @author LeiJia  
	 * @return JSONObject    返回类型
	 */
	@RequestMapping(value="/updateProduct")
	@ResponseBody
	public JSONObject updateProduct(HttpServletRequest request,HttpServletResponse response){
		JSONObject json = new JSONObject();
		String id = getPara("id"); //购物车ID
		String quantity =getPara("quantity");
		try{
			if(Common.isEmpty(id) || Common.isEmpty(quantity)){
				json.put("flag", false);
				return json; 
			}	
			Cart cart = new Cart();
			cart.setId(id);
			cart.setQuantity(Integer.valueOf(quantity));
			cart.setIsDelete(Constants.CartProduct.IS_DELETEA);
			cart.setModifyDate(new Date());
		    int updateCart = cartService.updateCart(cart);
		    if(updateCart > 0){
		    	logger.info("修改商品数量成功!");
				cartService.updateSessionCookieCartCount(request,response);//更新session或cookie购物车中的商品数量
		        json.put("flag", true);
		    }else{
		    	logger.info("修改商品数量失败!");
		        json.put("flag", false);
		    }
		}catch(Exception e){
			e.printStackTrace();
			json.put("flag", false);
		}
		return json;
	}
	/**
	 * @Title: updateProductSku
	 * @Description: 修改购物车商品规格
	 * @date 2017年4月23日上午16:05:05
	 * @author LeiJia  
	 * @return JSONObject    返回类型
	 */
	@RequestMapping(value="/updateProductSkuInfo")
	@ResponseBody
	public JSONObject updateProductSkuInfo(HttpServletRequest request,HttpServletResponse response){
		JSONObject json = new JSONObject();
		String id = getPara("id"); //购物车ID
		String goods_sku_id =getPara("goods_sku_id");
		String goods_sku_info =getPara("goods_sku_info");
		try{
			if(Common.isEmpty(id) || Common.isEmpty(goods_sku_id) || Common.isEmpty(goods_sku_info)){
				json.put("flag", false);
				return json; 
			}	
			Cart cart = new Cart();
			cart.setId(id);
			cart.setGoods_sku_id(goods_sku_id);
			cart.setGoods_sku_info(goods_sku_info);
			cart.setIsDelete(Constants.CartProduct.IS_DELETEA);
			cart.setModifyDate(new Date());
		    int updateCart = cartService.updateCart(cart);
		    if(updateCart > 0){
		    	logger.info("修改商品规格信息成功!");
				cartService.updateSessionCookieCartCount(request,response);//更新session或cookie购物车中的商品数量
		        json.put("flag", true);
		    }else{
		    	logger.info("修改商品规格信息失败!");
		        json.put("flag", false);
		    }
		}catch(Exception e){
			e.printStackTrace();
			json.put("flag", false);
		}
		return json;
	}
	/**
	 * @Title  getGoodsStockBySkuValues
	 * @Description:根据商品规格值获取商品库存
	 * @param goods_sku_info
	 * @return
	 */
	@RequestMapping(value="getGoodsStockBySkuValues",method=RequestMethod.POST)
	@ResponseBody
	public Map<String,Object> getGoodsStockBySkuValues(Integer productId,String goods_sku_info){
		Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
		try{
			if( productId == null){
				DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_PRODUCT_ID_IS_NOT_NULL);
				return resultMap;
		    }
			String[] skuInfoArrs = {};
			if(Common.isNotEmpty(goods_sku_info)){
				skuInfoArrs = goods_sku_info.split(",");
			}

			GoodsStock stock = new GoodsStock();
			stock.setGoodsId(productId);
			int productStock = goodsService.getProductStock(stock,skuInfoArrs);	
		/*	for(String sku_value :skuInfoArrs){
				sku_value = sku_value.split(":")[1];
				GoodsStock stock = new GoodsStock();
				stock.setGoodsId(productId);
				stock.setSkuValue(sku_value);;
				Integer baseQuantit = cartService.selectBaseQuantity(stock);
				Integer saleBaseQuantity = cartService.selectSaleBaseQuantity(stock);
				if(baseQuantit == null || saleBaseQuantity == null){
					productStock =0;
				}
				productStock += baseQuantit-saleBaseQuantity;
			}*/
			resultMap.put("productId", productId);
			resultMap.put("goods_sku_info", goods_sku_info);
			resultMap.put("stock", productStock);
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SUCCESS);
		}catch(Exception e){
			e.printStackTrace();
			DataUtil.handleResultMap(resultMap, ExceptionEnum.DATA_SELECT);
		}
		return resultMap;
	}
	/**
	 * @title 判断是否有商品参与了促销活动
	 * @param productId
	 * @param itemnum
	 * @param marketPrice
	 * @return
	 */
	public boolean  productWhtherJoinPrivilege(Integer productId,int itemnum, BigDecimal marketPrice){
		//查询商品参与的促销活动
		List<PromotionGoodsSkuDto>  goodsProList = promotionService.getGoodsProInfo(productId);
		if(goodsProList != null && goodsProList.size() > 0){
			for(PromotionGoodsSkuDto goodsSkuDto : goodsProList){						
				List<PromotionDetailDto> goodsProDetailList = promotionService.selectProDetailByProId(goodsSkuDto.getPro_id());
				for(PromotionDetailDto proDetailDto :goodsProDetailList){
                    Date now_time = new Date(); //现在时间
				    Date pro_start = proDetailDto.getPro_start(); //促销开始时间
				    Date pro_end  = proDetailDto.getPro_end(); //促销结束时间
				    if(pro_start.getTime() <= now_time.getTime() && now_time.getTime() <= pro_end.getTime()){//活动未失效
						Map<String,Object> proDetailMap = new LinkedHashMap<String, Object>();
						//proDetailMap.put("proTitle", proDetailDto.getPro_title());//促销名称
						proDetailMap.put("proDetailId", proDetailDto.getPro_detail_id());
						proDetailMap.put("proDetailTitle", proDetailDto.getExt());//促销活动名称
						proDetailMap.put("proDetailNote", proDetailDto.getExt1());//促销活动备注
						String pro_type = proDetailDto.getPro_type();
						String pro_money = proDetailDto.getPro_money();
						String pro_count = proDetailDto.getPro_count();
						String pro_rate = proDetailDto.getPro_rate();								

						String pro_gooods = proDetailDto.getPro_goods();
						proDetailMap.put("productId", productId);
						proDetailMap.put("giftGoods", pro_gooods);//促销赠品商品ID英文逗号隔开
						proDetailMap(proDetailMap, pro_type, pro_money, pro_count, pro_rate, pro_gooods);//封装促销活动返回集合
						if(goodsWhetherMeetWholeActivity(pro_type,proDetailMap,itemnum, marketPrice)){
							return true;
						}
				    }
				}
			}
		}
		return false;
	}
	/**
	 * @title 判断订单中的商品是否满足部分活动 
	 * @param pro_type
	 * @param proDetailMap
	 * @param itemnum //商品数量
	 * @param marketPrice //商品市场价
	 * @return
	 */
	public boolean goodsWhetherMeetWholeActivity(String pro_type, Map<String, Object> proDetailMap,int itemnum, BigDecimal marketPrice){
		boolean flag = false;
        BigDecimal totalAmount =  marketPrice.multiply(new BigDecimal(itemnum)).setScale(2, BigDecimal.ROUND_HALF_UP);
        switch(pro_type){
			case "0": //订单满减
				if(proDetailMap.get("mustQuantity") != null){
					//System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if(itemnum >=Integer.valueOf(proDetailMap.get("mustQuantity").toString())){
						flag = true;
					}
				}
				break;
			case "1": //商品满减
				if(proDetailMap.get("mustQuantity") != null){
					//System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if( totalAmount.compareTo(new BigDecimal(proDetailMap.get("mustQuantity").toString())) >=0 ){
						flag = true;
					}
				}
				break;
			case "2": //商品满赠
				if(proDetailMap.get("mustQuantity") != null){
				//	System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if( itemnum >= Integer.valueOf(proDetailMap.get("mustQuantity").toString()) ){
						flag = true;
					}
				}
				break;
			case "3":  //商品打折
				if(proDetailMap.get("mustQuantity") != null){
					//System.out.print("itemnum: "+ itemnum +"\n" + "mustQuantity: " + Integer.valueOf(proDetailMap.get("mustQuantity").toString()));
					if( itemnum >= Integer.valueOf(proDetailMap.get("mustQuantity").toString()) ){
						flag = true;
					}
				}
				break;
	        }
		return flag;
	}
	
	/**
	 * 封装促销活动返回集合
	 * @param proDetailMap
	 * @param pro_type
	 * @param pro_money
	 * @param pro_count
	 * @param pro_rate
	 * @param pro_gooods
	 * @return
	 */
	public Map<String, Object> proDetailMap(Map<String, Object> proDetailMap,
			String pro_type, String pro_money, String pro_count,
			String pro_rate, String pro_gooods) {
		List<Goods> goodsList = new ArrayList<Goods>();// 满赠商品列表
		String[] goods_ids = null;
		if (Common.isNotEmpty(pro_gooods)) {
			goods_ids = pro_gooods.split(",");
			for (String goods_id : goods_ids) {
				Goods goods = goodsService.selectByPrimaryKey(Integer
						.valueOf(goods_id));
				goodsList.add(goods);
			}
		}
		switch (pro_type) {
		case "0": // 订单满减
			if (Common.isNotEmpty(pro_money)) {
				proDetailMap.put("mustQuantity", pro_money.split(":")[0]);
				proDetailMap.put("discountAmount", pro_money.split(":")[1]);
			}
			break;
		case "1": // 商品满减
			if (Common.isNotEmpty(pro_count)) {
				proDetailMap.put("mustQuantity ", pro_count.split(":")[0]);
				proDetailMap.put("discountAmount", pro_count.split(":")[1]);
			}
			break;
		case "2": // 商品满赠
			if (Common.isNotEmpty(pro_count)) {
				proDetailMap.put("mustQuantity", pro_count.split(":")[0]);
				proDetailMap.put("giveNumber", pro_count.split(":")[1]);
				proDetailMap.put("giveList", goodsList);
			}
			break;
		case "3": // 商品打折
			if (Common.isNotEmpty(pro_count)) {
				proDetailMap.put("mustQuantity", pro_count);// 商品满足数量
				proDetailMap.put("discountRate", pro_rate);// 商品打折率
			}
		}
		return proDetailMap;
	}

}
